package com.cci.kangdao.service.impl;


import com.cci.kangdao.cipapi.ActionEnum;
import com.cci.kangdao.cipapi.CipApiUtils;
import com.cci.kangdao.dao.MonthlyReportMessageRecordTMapper;
import com.cci.kangdao.dao.ServiceAgrementDao;
import com.cci.kangdao.dao.UserTDao;
import com.cci.kangdao.dao.model.CustomerEngineRelT;
import com.cci.kangdao.dao.model.MonthlyReportMessageRecordT;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.model.NotifyRecordInfo;
import com.cci.kangdao.model.PublicSendNotifyRequest;
import com.cci.kangdao.service.AsyncCrmService;
import com.cci.kangdao.service.CustomerEngineRelTService;
import com.cci.kangdao.service.InviteUserService;
import com.cci.kangdao.utilTool.BeanUtils;
import com.cci.kangdao.utilTool.HttpUtils;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.gexin.fastjson.JSON;
import com.gexin.fastjson.JSONArray;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//终端用户和发动机关系表接口
@Service("CustomerEngineRelTService")
public class CustomerEngineRelTServiceImpl implements CustomerEngineRelTService{

	private Logger log = Logger.getLogger(this.getClass().getName());

	@Value("${mc.messagePushUrl}")
	private String messagePushUrl;
	@Resource
	private MonthlyReportMessageRecordTMapper monthlyReportMessageRecordTMapper;
	@Resource
	private InviteUserService inviteUserService;
	@Resource
	private ServiceAgrementDao saDao;
	@Resource
	private UserTDao userTDao;
	@Resource
	private AsyncCrmService asyncCrmService;

	/**
	 * 推送导航驾驶行为建议车联网消息
	 */
	@Override
	public void FuelTripReportPush(PublicSendNotifyRequest request, String userName,String params){
		List<NotifyRecordInfo> recordList = new ArrayList<>();
		String jsonString = JSONArray.toJSON(request).toString();
		String url = String.format(messagePushUrl + "/api/notify/publicSendNotify");
		String response = HttpUtils.postJson(url, jsonString, new ResponseHandler<String>() {
			@Override
			public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
				if (response.getStatusLine().getStatusCode() == 200) {
					HttpEntity httpEntity = response.getEntity();
					return EntityUtils.toString(httpEntity);
				} else {
					log.error( "获取发送消息推送接口参数：" + jsonString + "；返回结果：" + response);
				}
				return null;
			}
		});
		log.info( "发送消息推送接口返回数据：" + response);
		if (StringUtils.isNotEmpty(response)) {
			Map<String, Object> maps = (Map) JSON.parse(response);
			if (null != maps.get("status") && "0".equals(maps.get("status").toString())) {
				recordList = JSON.parseArray(maps.get("data").toString(), NotifyRecordInfo.class);
			}
		}
		if (recordList.size() > 0) {
			for (NotifyRecordInfo record : recordList) {
				if (userName.equals(record.getUserName())) {
					MonthlyReportMessageRecordT monthlyReport = new MonthlyReportMessageRecordT();
					monthlyReport.setReceiverId(request.getUserIdList().get(0));
					monthlyReport.setContent(request.getContent());
					monthlyReport.setSendType(2);
					monthlyReport.setStatus(record.getStatus() == 1 ? record.getStatus() : 2);
					monthlyReport.setExceptionInfo(record.getResult());
					monthlyReport.setIsRead(0);
					monthlyReport.setFlag(0);
					monthlyReport.setCreator(request.getUserIdList().get(0));
					monthlyReport.setCreateTime(LocalTimeUtil.getRealCurrentTime());
					monthlyReport.setMessageType(3);
					monthlyReport.setParams(params);
					monthlyReportMessageRecordTMapper.insert(monthlyReport);
				}
			}
		}
	}

	/**
	 * 绑车其他操作
	 * @param engineList
	 * @return
	 */
	@Override
	public void vehicleOtherOperations(List<CustomerEngineRelT> engineList) {
		if(CollectionUtils.isNotEmpty(engineList)) {
			log.info("外部绑车其他操作:"+engineList);
			List<CustomerEngineRelT> engineRelList = BeanUtils.convertList(engineList,CustomerEngineRelT.class);
			for(CustomerEngineRelT customerEngineRelT : engineRelList){
				String esn = customerEngineRelT.getEsn();
				String plateNumber = customerEngineRelT.getPlateNumber();
				//百万圆桌绑车
				inviteUserService.addBwyzBind(esn, customerEngineRelT.getUserId());
				Long count = saDao.isSignAgreement(customerEngineRelT.getUserId(), LocalTimeUtil.getRealCurrentTime());
				if (count > 0) {//用户如果签署了主动服务协议，将发动机信息同步至salesforce
					UserT userT = userTDao.selectById(customerEngineRelT.getUserId());
					asyncCrmService.syncServiceAgreementAndEngineToCRM(userT, esn, true, true);
					//同步esn给cip
					List<String> esnList = new ArrayList<>();
					esnList.add(esn);
					CipApiUtils.getCipServiceApi().synchronizationEsn(ActionEnum.ADD.getValue(), esnList,null);
				}
			}
		}
	}
}
